// inventory.js
const app = getApp()
const { API } = require('../../../utils/api.js')

Page({
  data: {
    inventoryData: [], // 从后端API获取真实库存数据
    editingIndex: -1,
    tempStock: '',
    tempMinStock: '',
    tempMaxStock: '',
    showTonsModal: false,
    currentFuelIndex: -1,
    currentFuelName: '',
    currentFuelType: '',
    customTons: ''
  },

  onLoad() {
    this.loadInventory()
  },

  onShow() {
    // 每次显示页面时重新加载库存，确保数据最新
    this.loadInventory()
  },

  async loadInventory() {
    try {
      wx.showLoading({
        title: '加载库存数据...'
      })

      console.log('开始从后端获取库存数据...')
      
      // 从后端获取最新的库存数据
      const inventoryList = await API.admin.getInventory()
      
      console.log('后端返回的库存数据:', inventoryList)
      
      if (inventoryList && inventoryList.length > 0) {
        // 格式化库存数据，添加前端需要的字段
        const formattedInventory = inventoryList.map(item => {
          const typeCode = this.getFuelTypeCode(item.fuelType)
          const stockStatus = this.getStockStatus(item.stock, item.minStock, item.maxStock)
          
          return {
            ...item,
            // 保持原有字段名
            id: item.id,
            fuelType: item.fuelType,
            stock: parseFloat(item.stock),
            minStock: parseFloat(item.minStock),
            maxStock: parseFloat(item.maxStock),
            // 添加前端需要的字段
            name: item.fuelType,
            type: typeCode,
            capacity: parseFloat(item.maxStock),
            density: this.getFuelDensity(typeCode),
            stockStatus: stockStatus,
            stockPercentage: this.getStockPercentage(item.stock, item.maxStock),
            stockInTons: this.convertLitersToTons(item.stock, typeCode)
          }
        })
        
        this.setData({
          inventoryData: formattedInventory
        })
        
        // 缓存到本地
        wx.setStorageSync('inventoryData', formattedInventory)
        console.log('格式化后的库存数据:', formattedInventory)
        
        // 检查库存警告
        this.checkStockWarnings(formattedInventory)
        
      } else {
        console.log('后端返回的库存数据为空')
        wx.showToast({
          title: '暂无库存数据',
          icon: 'none'
        })
      }
      
      wx.hideLoading()
    } catch (error) {
      wx.hideLoading()
      console.error('获取库存数据失败:', error)
      
      let errorMessage = '获取库存数据失败'
      if (error.statusCode === 401) {
        errorMessage = '登录已过期，请重新登录'
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/login/login'
          })
        }, 2000)
      } else if (error.statusCode === 403) {
        errorMessage = '没有权限查看库存数据'
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'error',
        duration: 3000
      })
      
      // 如果API调用失败，尝试从本地缓存获取
      const storedInventory = wx.getStorageSync('inventoryData')
      if (storedInventory && storedInventory.length > 0) {
        console.log('使用缓存的库存数据:', storedInventory)
        this.setData({
          inventoryData: storedInventory
        })
      }
    }
  },

  // 获取库存状态
  getStockStatus(stock, minStock, maxStock) {
    const percentage = (stock / maxStock) * 100
    if (percentage <= 20) return 'critical'
    if (percentage <= 50) return 'warning'
    return 'normal'
  },

  // 获取库存百分比
  getStockPercentage(stock, maxStock) {
    return Math.round((stock / maxStock) * 100)
  },

  // 升转换为吨
  convertLitersToTons(liters, fuelType) {
    const density = this.getFuelDensity(fuelType)
    const tons = (liters * density) / 1000
    return Math.round(tons * 100) / 100 // 保留两位小数
  },

  // 检查库存警告
  checkStockWarnings(inventoryData) {
    const lowStockItems = inventoryData.filter(item => item.stock <= item.minStock)
    if (lowStockItems.length > 0) {
      const itemNames = lowStockItems.map(item => item.fuelType).join('、')
      wx.showModal({
        title: '库存警告',
        content: `以下油品库存不足，请及时补货：\n${itemNames}`,
        showCancel: false,
        confirmText: '知道了'
      })
    }
  },

  // 根据油品名称获取类型代码
  getFuelTypeCode(fuelType) {
    const typeMap = {
      '92号汽油': '92',
      '95号汽油': '95', 
      '98号汽油': '98',
      '0号柴油': '0' // 修正柴油的类型代码
    }
    return typeMap[fuelType] || fuelType
  },

  // 获取油品密度 (kg/L)
  getFuelDensity(fuelType) {
    const densityMap = {
      '92': 0.75,
      '95': 0.75,
      '98': 0.75,
      '0': 0.84, // 柴油密度
      'diesel': 0.84
    }
    return densityMap[fuelType] || 0.75
  },

  startEdit(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.inventoryData[index]
    
    this.setData({
      editingIndex: index,
      tempStock: item.stock.toString(),
      tempMinStock: item.minStock.toString(),
      tempMaxStock: item.maxStock.toString()
    })
  },

  onStockInput(e) {
    this.setData({
      tempStock: e.detail.value
    })
  },

  onMinStockInput(e) {
    this.setData({
      tempMinStock: e.detail.value
    })
  },

  onMaxStockInput(e) {
    this.setData({
      tempMaxStock: e.detail.value
    })
  },

  async saveInventory() {
    const { editingIndex, tempStock, tempMinStock, tempMaxStock, inventoryData } = this.data
    
    if (!tempStock || isNaN(parseFloat(tempStock))) {
      wx.showToast({
        title: '请输入有效库存',
        icon: 'error'
      })
      return
    }

    if (!tempMinStock || isNaN(parseFloat(tempMinStock))) {
      wx.showToast({
        title: '请输入有效最小库存',
        icon: 'error'
      })
      return
    }

    if (!tempMaxStock || isNaN(parseFloat(tempMaxStock))) {
      wx.showToast({
        title: '请输入有效最大库存',
        icon: 'error'
      })
      return
    }

    const stock = parseFloat(tempStock)
    const minStock = parseFloat(tempMinStock)
    const maxStock = parseFloat(tempMaxStock)

    if (stock > maxStock) {
      wx.showToast({
        title: '当前库存不能超过最大库存',
        icon: 'error'
      })
      return
    }

    if (minStock > maxStock) {
      wx.showToast({
        title: '最小库存不能超过最大库存',
        icon: 'error'
      })
      return
    }

    const currentItem = inventoryData[editingIndex]

    try {
      wx.showLoading({
        title: '更新库存中...'
      })

      // 调用后端API更新数据库中的库存
      const updatedInventory = await API.admin.updateInventory({
        id: currentItem.id,
        stock: stock
      })

      wx.hideLoading()

      // 更新本地数据
      const updatedData = [...inventoryData]
      updatedData[editingIndex] = {
        ...updatedData[editingIndex],
        stock: updatedInventory.stock,
        minStock: updatedInventory.minStock,
        maxStock: updatedInventory.maxStock,
        capacity: updatedInventory.maxStock
      }

      this.setData({
        inventoryData: updatedData,
        editingIndex: -1,
        tempStock: '',
        tempMinStock: '',
        tempMaxStock: ''
      })

      // 更新本地缓存
      wx.setStorageSync('inventoryData', updatedData)
      
      wx.showToast({
        title: '库存更新成功',
        icon: 'success'
      })

      console.log(`${currentItem.name} 库存已更新: ${stock}升`)
      
    } catch (error) {
      wx.hideLoading()
      console.error('更新库存失败:', error)
      
      let errorMessage = '库存更新失败，请稍后重试'
      if (error.statusCode === 401) {
        errorMessage = '登录已过期，请重新登录'
      } else if (error.statusCode === 403) {
        errorMessage = '没有权限执行此操作'
      }
      
      wx.showModal({
        title: '更新失败',
        content: errorMessage,
        showCancel: false
      })
    }
  },

  cancelEdit() {
    this.setData({
      editingIndex: -1,
      tempStock: '',
      tempMinStock: '',
      tempMaxStock: ''
    })
  },

  addStockByTons(e) {
    const index = e.currentTarget.dataset.index
    const tons = parseFloat(e.currentTarget.dataset.tons)
    const fuelItem = this.data.inventoryData[index]
    const liters = this.convertTonsToLiters(tons, fuelItem.type)
    
    wx.showModal({
      title: '补充库存',
      content: `确定要补充${tons}吨(${liters}升)库存吗？`,
      success: (res) => {
        if (res.confirm) {
          this.addStockInLiters(index, liters)
        }
      }
    })
  },

  showCustomTonsModal(e) {
    const index = e.currentTarget.dataset.index
    const fuelItem = this.data.inventoryData[index]
    
    this.setData({
      showTonsModal: true,
      currentFuelIndex: index,
      currentFuelName: fuelItem.name,
      currentFuelType: fuelItem.type,
      customTons: ''
    })
  },

  hideTonsModal() {
    this.setData({
      showTonsModal: false,
      currentFuelIndex: -1,
      currentFuelName: '',
      currentFuelType: '',
      customTons: ''
    })
  },

  onCustomTonsInput(e) {
    this.setData({
      customTons: e.detail.value
    })
  },

  confirmAddTons() {
    const { currentFuelIndex, customTons, currentFuelType } = this.data
    
    if (!customTons || isNaN(parseFloat(customTons))) {
      wx.showToast({
        title: '请输入有效吨数',
        icon: 'error'
      })
      return
    }

    const tons = parseFloat(customTons)
    const liters = this.convertTonsToLiters(tons, currentFuelType)
    
    wx.showModal({
      title: '确认添加',
      content: `确定要添加${tons}吨(${liters}升)库存吗？`,
      success: (res) => {
        if (res.confirm) {
          this.addStockInLiters(currentFuelIndex, liters)
          this.hideTonsModal()
        }
      }
    })
  },

  async addStockInLiters(index, liters) {
    const inventoryData = this.data.inventoryData
    const currentItem = inventoryData[index]
    const newStock = Math.min(
      currentItem.stock + liters,
      currentItem.maxStock
    )
    
    if (newStock >= currentItem.maxStock) {
      wx.showToast({
        title: '已达到储罐容量上限',
        icon: 'none'
      })
    }

    try {
      wx.showLoading({
        title: '补充库存中...'
      })

      // 调用后端API更新库存
      const updatedInventory = await API.admin.updateInventory({
        id: currentItem.id,
        stock: newStock
      })

      wx.hideLoading()

      // 更新本地数据
      const updatedData = [...inventoryData]
      updatedData[index] = {
        ...updatedData[index],
        stock: updatedInventory.stock
      }

      this.setData({
        inventoryData: updatedData
      })

      // 更新本地缓存
      wx.setStorageSync('inventoryData', updatedData)
      
      wx.showToast({
        title: '库存补充成功',
        icon: 'success'
      })

      console.log(`${currentItem.name} 库存已补充至: ${updatedInventory.stock}升`)
      
    } catch (error) {
      wx.hideLoading()
      console.error('补充库存失败:', error)
      
      wx.showModal({
        title: '补充失败',
        content: '库存补充失败，请稍后重试',
        showCancel: false
      })
    }
  },



  // 将吨转换为升
  convertTonsToLiters(tons, fuelType) {
    if (!tons || isNaN(parseFloat(tons))) return 0
    const density = this.getFuelDensity(fuelType)
    const liters = (parseFloat(tons) * 1000) / density
    return Math.round(liters)
  }
})